import axios from 'axios'
import { getBaseUrl } from './env'
class HttpRequest {
  constructor () {
    this.baseURL = getBaseUrl(process.env.NODE_ENV)
    this.timeout = 5000,
    this.withCredentials = true
  }
  static _instance = null
  // 获取单例，避免有多个httpRequest的实例
  static getSingle () {
    this._instance || (this._instance = new HttpRequest())
    return this._instance
  }
  // axios实例的基础参数配置
  getInsideConfig () {
    const config = {
      baseURL: this.baseURL,
      timeout: this.timeout,
      withCredentials: this.withCredentials,
      headers: {
        Authorization: '', // 是否获取token
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      // 对数据进行转换
      transformRequest: [data => JSON.stringify(data)],
      transformResponse: [data => JSON.parse(data)]
    }
    return config
  }
  // 拦截请求和响应
  getInterceptors (instance) {
    // 请求拦截
    instance.interceptors.request.use(config => {
    // 清除get请求的缓存, 加时间戳
    (~config.method && ~config.params) && Object.assign(config, {
      params: {
        timestamp: +new Date()
      }
    }) || Object.assign(config.params, {
      timestamp: +new Date()
    })
      return config
    }, err => Promise.reject(err))
    // 响应拦截
    instance.interceptors.response.use(response => {
      return response.data
    }, err => Promise.reject(err))
  }
  request (options) {
    const instance = axios.create()
    // 合并参数
    options = Object.assign(this.getInsideConfig(), options)
    this.getInterceptors(instance)
    return instance(options)
  }
}
const axiosRequest = HttpRequest.getSingle()
export default axiosRequest
